package com.minivision.sdktestdemo.ui;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.TextView;

import com.minivision.sdktestdemo.R;
import com.minivision.sdktestdemo.bean.MusicBean;
import com.minivision.sdktestdemo.controler.ui.activity.MusicMiniPlayControler;
import com.minivision.sdktestdemo.controler.ui.list.MusicListControler;
import com.minivision.sdktestdemo.controler.ui.viewpager.MusicNavControler;
import com.minivision.sdktestdemo.event.DataModificationEvent;
import com.minivision.sdktestdemo.event.PlayMusicEvent;
import com.minivision.sdktestdemo.ui.view.MusicCtrlPopContentView;
import com.minivision.sdktestdemo.ui.view.PopupView;

import org.greenrobot.eventbus.EventBus;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link MusicListFragment.OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link MusicListFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class MusicListFragment extends Fragment implements MusicItemRecyclerAdapter.OnItemListener,
        MusicItemRecyclerAdapter.onPlayEventChanged, OnFragmentUpdatedListener, WrapAdapter.OnHeadClickListener {
    // TODO: Rename parameter arguments, choose names that match

    private static final String TOOL_BAR = "tool_bar";

    // TODO: Rename and change types of parameters
    private String mTitle;
    private String mParam2;

    private OnFragmentInteractionListener mListener;

    private MusicControlHandler.onProgressUpdated mProgressListener;

    public MusicListFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment MusicListFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static MusicListFragment newInstance(String param1, boolean showToolBar) {
        MusicListFragment fragment = new MusicListFragment();
        Bundle args = new Bundle();
        args.putString(MusicNavControler.PARAM1, param1);
        args.putBoolean(TOOL_BAR, showToolBar);
        fragment.setArguments(args);
        return fragment;
    }

    private boolean mShowToolBar;
    private boolean isInit;
    private MusicNavFragment.ToolBarHelper mHelper;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mTitle = getArguments().getString(MusicNavControler.PARAM1);
            mShowToolBar = getArguments().getBoolean(TOOL_BAR);
        }
        mExecutor = Executors.newSingleThreadExecutor();
        mPopView = new PopupView(getActivity(), new MusicCtrlPopContentView(getActivity()));
    }

    @Bind(R.id.music_list)
    RecyclerView mRecyclerView;

    private WrapAdapter mAdapter;

    //private MusicItemRecyclerAdapter mAdapter;

    private MusicListControler mMusicListControler;

    private PopupView mPopView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_music_list, container, false);
        ButterKnife.bind(this, view);
        initData();
        initView();
        return view;
    }

    private List<MusicBean> mList;

    private void initData() {
        mMusicListControler = mMusicListControler == null ? new MusicListControler(getActivity(), mList) : mMusicListControler;
        if (mAdapter == null) {
            MusicItemRecyclerAdapter adapter = new MusicItemRecyclerAdapter(this, mMusicListControler);
            adapter.setItemClickListener(this);
            mAdapter = new WrapAdapter(adapter);
            mAdapter.setHeadViewId(R.layout.layout_item_head);
            mAdapter.setHeadListener(this);
        }
    }

    private void initToolBar() {
        if (mShowToolBar) {
            setHasOptionsMenu(true);
        }
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        final AppCompatActivity appCompatActivity = (AppCompatActivity) getActivity();
        menu.setGroupVisible(R.id.system_group, false);
        mHelper.getToolbar().setLogo(null);
        mHelper.getToolbar().setTitle(mTitle);
        mHelper.getToolbar().setNavigationIcon(R.drawable.ic_action_arrow_left);
        mHelper.getToolbar().setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                appCompatActivity.onBackPressed();
            }
        });
        mHelper.getToolbar().setOnMenuItemClickListener(null);
        super.onCreateOptionsMenu(menu, inflater);
    }

    private void initView() {
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRecyclerView.setAdapter(mAdapter);
        //mRecyclerView.addItemDecoration(new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL_LIST));
        initToolBar();
        initProgress();
        if (mEvent != null) {
            update(mEvent);
        }
    }

    @Bind(R.id.loading)
    ViewGroup mStubLoad;

    @Bind(R.id.tv_empty)
    TextView mTvEmpty;

    private ExecutorService mExecutor;

    public void initProgress() {
        if (mAdapter.isEmpty()) {
            mStubLoad.setVisibility(View.VISIBLE);
            ImageView imageView = (ImageView) mStubLoad.findViewById(R.id.img_anim);
            AnimationDrawable drawable = (AnimationDrawable) imageView.getDrawable();
            drawable.start();
        }
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
            mProgressListener = (MusicControlHandler.onProgressUpdated) context;
            mPlayListGetter = (MusicMiniPlayControler.PlayListGetter) context;
            mHelper = (MusicNavFragment.ToolBarHelper) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mExecutor.shutdownNow();
        mListener = null;
        mProgressListener = null;
        mPlayListGetter = null;
        mHelper = null;
    }

    @Override
    public void onDestroyView() {
        ButterKnife.unbind(this);
        super.onDestroyView();
    }

    private PlayMusicEvent mEvent;

    public void setEvent(PlayMusicEvent event) {
        if (mEvent == null) {
            mEvent = event;
        } else {
            mEvent.setPlayEvent(event);
        }
    }

    public void setListBean(List<MusicBean> list) {
        mList = list;
    }

    public PlayMusicEvent getPlayEvent(int position) {
        String uri = mMusicListControler.getPath(position);
        //获取映射后的position
        Uri albumUri = mList.get(position).getmPicUri() == null ? Uri.EMPTY : mList.get(position).getmPicUri();
        PlayMusicEvent event = new PlayMusicEvent(mList.get(position).getmPath(),
                mList.get(position).getmMusicName(), mList.get(position).getmSingerName(),
                PlayMusicEvent.PLAY, albumUri, mList.get(position).getmLen());
        return event;
    }

    @Override
    public String getKeyUri() {
        if (mEvent == null) {
            return "";
        } else {
            return mEvent.mUri;
        }
    }

    private MusicMiniPlayControler.PlayListGetter mPlayListGetter;

    @Override
    public int getType() {
        return MusicItemRecyclerAdapter.MUSIC_LIST;
    }

    @Override
    public void onItemClick(View v, int position) {
        PlayMusicEvent event = getPlayEvent(position);
        if (mEvent != null && mEvent.mUri.equals(event.mUri)) {
            mListener.checkDetailActivity();
        } else {
            setPlayEvent(event);
            List<MusicBean> list = mPlayListGetter.getPlayList();
            if (list != null && isListEqual(list, mMusicListControler.getBeans())) {
                event.mStatus = PlayMusicEvent.PLAY;
                mAdapter.notifyDataSetChanged();
                //拷贝对应的数据
                EventBus.getDefault().post(event);
            } else {
                DataModificationEvent e = new DataModificationEvent(mMusicListControler.getBeans(), DataModificationEvent.ACTION_GROUP_PLAY);
                EventBus.getDefault().post(e);
            }
        }
    }

    @Override
    public void onMoreItemClick(int position) {
        if (mPlayListGetter.getPlayList() == null) {
            mPopView.show(mMusicListControler.getBeans(), mMusicListControler.getBeans().get(position));
        } else {
            if (!isListEqual(mPlayListGetter.getPlayList(), mMusicListControler.getBeans())) {
                mPopView.show(mMusicListControler.getBeans(), mMusicListControler.getBeans().get(position));
            } else {
                mPopView.show(null, mMusicListControler.getBeans().get(position));
            }
        }
    }

    boolean isListEqual(List<MusicBean> src, List<MusicBean> tar) {
        Set<MusicBean> set = new HashSet<>(src);
        if (set.size() != tar.size())
            return false;
        boolean flag = true;
        for (MusicBean bean : tar) {
            if (!set.contains(bean)) {
                flag = false;
                break;
            }
        }
        return flag;
    }

    @Override
    public void update(PlayMusicEvent event) {
        setPlayEvent(event);
        if (mMusicListControler != null && mMusicListControler.notifyDataChanged()) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mAdapter.notifyDataSetChanged();
//                    mAdapter.notifyItemRangeInserted(mAdapter.getItemCount(), );
                    ImageView imageView = (ImageView) mStubLoad.findViewById(R.id.img_anim);
                    AnimationDrawable drawable = (AnimationDrawable) imageView.getDrawable();
                    drawable.stop();
                    mStubLoad.setVisibility(View.GONE);
                    if (mAdapter.getItemCount() == 0) {
                        mTvEmpty.setVisibility(View.VISIBLE);
                    } else {
                        mTvEmpty.setVisibility(View.GONE);
                    }
                }
            });
        }
    }

    @Override
    public void update(DataModificationEvent event) {
        //运行在子线程
        if (event.mAction == DataModificationEvent.ACTION_CHANGE) {
            mMusicListControler.adjustOrder();
        } else if (event.mAction == DataModificationEvent.ACTION_LIST_CLEAR) {
            mEvent.mUri = "";
        }
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mMusicListControler.notifyDataChanged()) {
                    mAdapter.notifyDataSetChanged();
                    mStubLoad.setVisibility(View.GONE);
                    if (mAdapter.isEmpty()) {
                        mAdapter.setHeadVisiable(false);
                        mTvEmpty.setVisibility(View.VISIBLE);
                    } else {
                        mTvEmpty.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (getUserVisibleHint()) {
            mExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    update(mEvent);
                }
            });
        }
    }

    @Override
    public void setPlayEvent(PlayMusicEvent event) {
        if (mEvent == null) {
            mEvent = event;
        } else {
            mEvent.setPlayEvent(event);
        }
    }

    @Override
    public void onClickHead() {
        DataModificationEvent event = new DataModificationEvent(mMusicListControler.getBeans(), DataModificationEvent.ACTION_GROUP_PLAY);
        EventBus.getDefault().post(event);
    }

    @Override
    public void onClickHeadMore() {
        mListener.onClickEditList(mMusicListControler.getBeans());
    }

    public interface OnFragmentInteractionListener {
        void checkDetailActivity();

        void onClickEditList(List<MusicBean> list);
    }
}

